import request from '../utils/request.js';

/**
 * 获取聊天会话列表
 * @returns {Promise} 返回聊天会话列表
 */
export const getSessionList = () => {
  console.log('调用获取会话列表API');
  return request.get('/api/chat/sessions');
};

/**
 * 获取聊天记录
 * @param {number} targetId - 目标用户ID
 * @returns {Promise} 返回聊天记录列表
 */
export const getChatHistory = (targetId) => {
  // 确保targetId是数字类型
  try {
    targetId = parseInt(targetId);
    console.log('调用获取聊天记录API，targetId:', targetId);
    return request.get('/api/chat/messages', {
      params: { targetId }
    });
  } catch (error) {
    console.error('获取聊天记录参数错误:', error);
    throw error;
  }
};

/**
 * 发送消息
 * @param {Object} sendMessageDTO - 发送消息DTO
 * @returns {Promise} 返回新消息ID
 */
export const sendMessage = (sendMessageDTO) => {
  try {
    if (sendMessageDTO.targetId) {
      sendMessageDTO.targetId = parseInt(sendMessageDTO.targetId);
    }
    console.log('调用发送消息API，参数:', sendMessageDTO);
    return request.post('/api/chat/send', sendMessageDTO);
  } catch (error) {
    console.error('发送消息参数错误:', error);
    throw error;
  }
};

/**
 * 标记消息为已读
 * @param {number} targetId - 目标用户ID
 * @returns {Promise} 返回是否成功
 */
export const markAsRead = (targetId) => {
  // 确保targetId是数字类型
  try {
    targetId = parseInt(targetId);
    console.log('调用标记已读API，targetId:', targetId);
    
    return request.post('/api/chat/markAsRead', {}, {
      params: { targetId }
    });
  } catch (error) {
    console.error('标记已读参数错误:', error);
    throw error;
  }
};

/**
 * 删除聊天会话
 * @param {number} sessionId - 会话ID
 * @returns {Promise} 返回是否成功
 */
export const deleteSession = (sessionId) => {
  try {
    sessionId = parseInt(sessionId);
    console.log('调用删除会话API，sessionId:', sessionId);
    return request.delete(`/api/chat/session/${sessionId}`);
  } catch (error) {
    console.error('删除会话参数错误:', error);
    throw error;
  }
};

/**
 * 删除指定会话的所有聊天记录
 * @param {number} sessionId - 会话ID
 * @returns {Promise} 返回是否成功
 */
export const deleteMessagesBySessionId = (sessionId) => {
  try {
    sessionId = parseInt(sessionId);
    console.log('调用删除会话消息API，sessionId:', sessionId);
    return request.delete(`/api/chat/messages/session/${sessionId}`);
  } catch (error) {
    console.error('删除会话消息参数错误:', error);
    throw error;
  }
};

/**
 * 删除与指定用户的所有聊天记录
 * @param {number} targetId - 目标用户ID
 * @returns {Promise} 返回是否成功
 */
export const deleteMessagesByUserId = (targetId) => {
  try {
    targetId = parseInt(targetId);
    console.log('调用删除用户消息API，targetId:', targetId);
    return request.delete(`/api/chat/messages/user/${targetId}`);
  } catch (error) {
    console.error('删除用户消息参数错误:', error);
    throw error;
  }
};
